<template>
  <div class="box_index">
    <!-- 搜索栏 -->
    <search-bar :options="searchBarOptions" style="padding-top:0;" />

    <!--分割线-->
    <div class="line"></div>

    <!-- 表格栏 -->
    <div class="table-box">
      <fast-table :options="fastTableOptions" :data="page.records" />
      <!-- 分页 -->
      <pagination
        :total="page.total"
        :current="page.current"
        :size="page.size"
        @changePageSize="changePageSize"
        @changePageNum="changePageNum"
      />
    </div>

    <!--弹窗-创建白名单用户 / 选择用户-->
    <el-dialog
      :close-on-click-modal="false"
      :title="dialogType2 == 1 ? $t('m.Add_whitelste') : $t('m.Select_users')"
      width="720px"
      :visible.sync="createDialog"
    >
      <div class="dialog_content" v-show="dialogType2 == 1">
        <div class="dialog_content1">{{ $t('m.Link_whitelist') }}*</div>
        <div class="dialog_content1" style=" padding-bottom: 0;">
          <el-form style="width:100%" label-position="top">
            <el-form-item prop="ruleId">
              <el-select
                style="width:100%"
                v-model="userItem.ruleId"
                :placeholder="$t('m.pleaseChoose')"
                filterable
                clearable
              >
                <el-option
                  v-for="item in ruleIdOptions"
                  :key="item.id"
                  :value="item.id"
                  :label="
                    (item.branchName ? item.branchName : $t('m.Platform')) +
                      '  ' +
                      $t('m.Free_duration_order2') +
                      (item.freeDuration ? item.freeDuration : '0') +
                      ($cache.getLang() == 'CN' ? '' : ' ') +
                      (item.freeDuration > 1 ? $t('m.hour4') : $t('m.hour3')) +
                      '  ' +
                      (item.deposit ? $t('m.No_deposit_card') : '')
                  "
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div>
          <el-button class="el_button" size="small" @click="dialogType2 = 2">{{
            $t('m.Select_users')
          }}</el-button>
        </div>
        <div class="el_table_div" style="padding:0;margin-bottom: 20px;">
          <el-table
            :data="
              whiteList2
                ? whiteList2.slice(
                    (whiteLists.pageNum - 1) * whiteLists.pageSize,
                    whiteLists.pageNum * whiteLists.pageSize
                  )
                : whiteList2
            "
          >
            <emptydata slot="empty" v-if="whiteList2.length == 0" />
            <el-table-column
              :label="$t('m.User_ID')"
              prop="ucode"
              min-width="120"
              fixed
            ></el-table-column>
            <el-table-column
              :label="$t('m.Users_Details_PhoneNo')"
              prop="phone"
              min-width="150"
            >
              <template #default="scope">
                <span v-if="scope.row.phone"
                  ><span v-show="scope.row.phone">(+{{ scope.row.code }})</span
                  >{{ scope.row.phone | maskedPhone }}</span
                ><span v-if="!scope.row.phone">--</span>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('m.Email')"
              prop="email"
              min-width="150"
            >
              <template #default="scope">
                <span v-if="scope.row.email">
                  {{ scope.row.email | maskedEmail }}
                </span>
                <span v-if="!scope.row.email">--</span>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              :label="$t('m.Users_Details_Operation')"
              min-width="108"
            >
              <template slot-scope="scope">
                <el-button
                  type="text"
                  style="color:var(--text-color)"
                  @click.native="deleteUser(scope.row, 1)"
                >
                  {{ $t('m.delete') }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div style="text-align: right;">
          <el-pagination
            background
            layout="prev, pager, next"
            @current-change="handleCurrentChange2"
            :current-page.sync="whiteLists.pageNum"
            :page-size="whiteLists.pageSize"
            :total="whiteList2.length"
          >
          </el-pagination>
        </div>
      </div>
      <div class="dialog_content" v-show="dialogType2 == 2">
        <div class="dialog_content1">{{ $t('m.Set_Validity_period') }}*</div>
        <div class="dialog_content1" style=" padding-bottom: 0;">
          <el-form style="width:100%" label-position="top">
            <el-form-item prop="days">
              <el-select
                style="width:100%"
                v-model="batchParams.days"
                :placeholder="$t('m.pleaseChoose')"
                filterable
                clearable
              >
                <el-option
                  v-for="item in periodOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="list_div">
          <div class="page_list_div" style="padding:0 0 8px 0;">
            <el-form class="page_list_top" label-position="right">
              <el-form-item class="page_list_top">
                <el-input
                  :placeholder="$t('m.User_Phone_Email')"
                  prefix-icon="el-icon-search"
                  clearable
                  v-model="params1.search"
                />
              </el-form-item>
              <el-form-item class="page_list_top page_list_search">
                <el-button
                  class="search_button reset_button"
                  @click="searchBtn"
                  >{{ $t('m.search_') }}</el-button
                >
              </el-form-item>
              <el-form-item class="page_list_top">
                <el-button class="reset_button" @click="refreshBtn">{{
                  $t('m.refresh')
                }}</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div
          v-if="dialogType2 == 2 && usersData.length == 0 && searchType == 2"
          class="refund_div"
          style="margin:0;"
        >
          {{ $t('m.Account_does_not_exist') }}
        </div>
        <div
          class="dialog_content1"
          style="padding: 0;"
          v-if="dialogType2 == 2 && usersData.length > 0 && searchType == 2"
        >
          <span style="padding-right: 16px;">{{ usersData[0].ucode }}</span>
          <span v-if="usersData[0].phone" style="padding-right: 16px;"
            >{{ '+' + usersData[0].code }}
            {{ usersData[0].phone | maskedPhone }}</span
          >
          <span v-if="usersData[0].email">
            {{ usersData[0].email | maskedEmail }}
          </span>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeCreate" class="cancel_btn">{{
          $t('m.cancel')
        }}</el-button>
        <el-button
          type="primary"
          @click="confirmCreate"
          class="cancel_btn confirm_btn"
          >{{ $t('m.confirm_') }}</el-button
        >
      </div>
    </el-dialog>

    <!-- 编辑白名单用户-->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="editUserDialog"
      :title="$t('m.Edit_whitelisted')"
      width="520px"
      append-to-body
    >
      <div class="dialog_content">
        <div class="dialog_content1">{{ $t('m.Link_whitelist') }}*</div>
        <div class="dialog_content1" style=" padding-bottom: 0;">
          <el-form style="width:100%" label-position="top">
            <el-form-item prop="id">
              <el-select
                style="width:100%"
                v-model="userItem.ruleId"
                :placeholder="$t('m.pleaseChoose')"
                filterable
                clearable
              >
                <el-option
                  v-for="item in ruleIdOptions"
                  :key="item.id"
                  :label="
                    (item.branchName ? item.branchName : $t('m.Platform')) +
                      '  ' +
                      $t('m.Free_duration_order2') +
                      (item.freeDuration ? item.freeDuration : '0') +
                      ($cache.getLang() == 'CN' ? '' : ' ') +
                      (item.freeDuration > 1 ? $t('m.hour4') : $t('m.hour3')) +
                      '  ' +
                      (item.deposit ? $t('m.No_deposit_card') : '')
                  "
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="dialog_content1">{{ $t('m.Set_Validity_period') }}*</div>
        <div class="dialog_content1">
          <el-form style="width:100%" label-position="top">
            <el-form-item prop="id" style=" margin-bottom: 0;">
              <el-select
                style="width:100%"
                v-model="userItem.days"
                :placeholder="$t('m.pleaseChoose')"
                filterable
                clearable
              >
                <el-option
                  v-for="item in periodOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancel_btn" @click="closeBtn">{{
          $t('m.cancel')
        }}</el-button>
        <el-button
          type="primary"
          class="cancel_btn confirm_btn"
          @click="editBtn"
          >{{ $t('m.confirm_') }}</el-button
        >
      </div>
    </el-dialog>

    <!--删除白名单-->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="deleteDialog"
      :title="$t('m.Delete_whitelisted')"
      width="520px"
      append-to-body
    >
      <div class="dialog_content">
        <div class="dialog_content1">
          {{ $t('m.Confirm_Delete_whitelisted') }}
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteDialog = false" class="cancel_btn">{{
          $t('m.cancel')
        }}</el-button>
        <el-button
          type="primary"
          @click="deleteUsers"
          class="cancel_btn confirm_btn"
          >{{ $t('m.confirm_') }}</el-button
        >
      </div>
    </el-dialog>

    <!-- 未创建白名单规则-->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="noneDialog"
      :title="$t('m.Add_whitelste')"
      width="520px"
      append-to-body
    >
      <div class="dialog_content">
        <div class="dialog_content1" style=" padding-bottom: 0;">
          {{ $t('m.No_whitelist_rules') }}
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="noneDialog = false" class="cancel_btn">{{
          $t('m.cancel')
        }}</el-button>
        <el-button
          type="primary"
          @click="toCreate"
          class="cancel_btn confirm_btn"
          >{{ $t('m.settings') }}</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import page from '@/mixins/page'
import pagination from '@/components/pagination.vue'
import SearchBar from '@/components/search-bar.vue'
import FastTable from '@/components/fast-table.vue'

export default {
  components: { FastTable, SearchBar, pagination },
  mixins: [page],
  data () {
    return {
      fastTableOptions: {},

      createDialog: false,

      whiteList2: [], // 选中用户
      whiteLists: {
        pageNum: 1,
        pageSize: 5
      },
      deleteDialog: false,
      dialogType2: 1,
      editUserDialog: false,
      noneDialog: false,
      userItem: {
        days: '',
        id: '',
        ruleId: ''
      },
      ruleIdOptions: [],
      batchParams: {
        days: 1,
        id: '',
        userIds: []
      }, //设置用户账号白名单状态的有效期
      usersData: [], // 搜索到的用户
      deleteType: '',
      deleteParams: '', // 删除参数
      params1: {
        search: ''
      },
      searchType: 1,
      //有效期选项
      periodOptions: [
        { value: 1, label: '1' + this.$t('m').Whitelist_Day },
        { value: 7, label: '1' + this.$t('m').Whitelist_Week },
        { value: 30, label: '1' + this.$t('m').Whitelist_Month },
        { value: 90, label: '3' + this.$t('m').Whitelist_Months },
        { value: 180, label: '6' + this.$t('m').Whitelist_Months },
        { value: 365, label: '12' + this.$t('m').Whitelist_Months }
      ],
      //时间选项
      durationOptions: [
        {
          value: 0,
          label:
            '0' +
            (this.$cache.getLang() == 'CN' ? '' : ' ') +
            this.$t('m').hour3
        },
        {
          value: 1,
          label:
            '1' +
            (this.$cache.getLang() == 'CN' ? '' : ' ') +
            this.$t('m').hour3
        },
        {
          value: 2,
          label:
            '2' +
            (this.$cache.getLang() == 'CN' ? '' : ' ') +
            this.$t('m').hour4
        },
        {
          value: 3,
          label:
            '3' +
            (this.$cache.getLang() == 'CN' ? '' : ' ') +
            this.$t('m').hour4
        },
        {
          value: 6,
          label:
            '6' +
            (this.$cache.getLang() == 'CN' ? '' : ' ') +
            this.$t('m').hour4
        },
        {
          value: 12,
          label:
            '12' +
            (this.$cache.getLang() == 'CN' ? '' : ' ') +
            this.$t('m').hour4
        },
        {
          value: 24,
          label:
            '24' +
            (this.$cache.getLang() == 'CN' ? '' : ' ') +
            this.$t('m').hour4
        },
        {
          value: 48,
          label:
            '48' +
            (this.$cache.getLang() == 'CN' ? '' : ' ') +
            this.$t('m').hour4
        },
        {
          value: 72,
          label:
            '72' +
            (this.$cache.getLang() == 'CN' ? '' : ' ') +
            this.$t('m').hour4
        }
      ],
      permissionsIds: []
    }
  },
  created () {
    this.$store.state.permissions.forEach(item => {
      this.permissionsIds.push(Number(this.$jsencrypt.decrypt(item)))
    })
    this.fastTableOptions = {
      columns: [
        {
          label: this.$t('m.User_ID'),
          prop: 'ucode',
          fixed: 'left'
        },

        {
          label: this.$t('m.Whitelist_ID'),
          prop: 'ruleCode'
        },

        {
          label: this.$t('m.invite_Type'),
          prop: 'type',
          formatter: row =>
            this.$format.stateFormat(row.type, this.$dict.whitelist.type)
        },
        {
          label: this.$t('m.Shop_name'),
          prop: 'branchName',
          formatter: row =>
            this.$format.strFormat(
              row.branchName ? row.branchName : this.$t('m.Platform')
            )
        },
        {
          label: this.$t('m.Validity_period'),
          minWidth: '200',
          prop: 'expireTime',
          formatter: row => this.$format.dateformat(row.expireTime)
        },

        {
          label: this.$t('m.status'),
          prop: 'state',
          switch: true,
          activeValue: 1,
          inactiveValue: 0,
          switchChange: this.editState
        },
        {
          label: this.$t('m.branch_Creationdate'),
          minWidth: '200',
          prop: 'createTime',
          formatter: row => this.$format.dateformat(row.createTime)
        },
        {
          label: this.$t('m.Update_date'),
          minWidth: '200',
          prop: 'updateTime',
          formatter: row => this.$format.dateformat(row.updateTime)
        },
        {
          operate: true,
          showcolumn: this.permissionsLists(152) || this.permissionsLists(153),
          display: 'dropdown',
          actions: [
            {
              label: this.$t('m.branch_Edit'),
              permission: row => this.permissionsLists(152),
              click: row => this.openDialog(row)
            },
            {
              label: this.$t('m.delete'),
              permission: row => this.permissionsLists(153),
              click: row => this.deleteUser(row, 2)
            }
          ]
        }
      ]
    }
    this.getSearchBar()
    this.getPage()
  },
  methods: {
    //权限id校验
    permissionsLists (val) {
      return this.permissionsIds.includes(val)
    },
    getSearchBar () {
      this.searchBarOptions = {
        search: this.search,
        bars: [
          {
            value: '',
            type: 'input',
            prop: 'search',
            placeholder: [
              this.$t('m.Whitelist_ID'),
              this.$t('m.Shop_name'),
              this.$t('m.User_ID')
            ].join(' / ')
          },
          {
            value: '',
            type: 'datePicker',
            prop: 'rangeTime',
            label: this.$t('m.branch_Creationdate')
          }
        ]
      }
    },

    getPage () {
      this.$api.whiteList.getPageUser(this.params, this.page).then(res => {
        if (this.$ok(res)) {
          this.page = res.data
        }
      })
    },

    // 获取白名单规则选项
    getRuleOptions (item) {
      let params = {
        ruleId: item ? item.ruleId : ''
      }
      this.$api.whiteList.getRuleOption(params).then(res => {
        if (this.$ok(res)) {
          this.ruleIdOptions = res.data
          // console.log(res.data);
          if (res.data.length == 0) {
            this.noneDialog = true
          } else {
            if (item) {
              this.userItem = {
                days: item.days,
                id: item.id,
                rentNum: item.rentNum || 1,
                ruleId: item.ruleId
              }
              this.editUserDialog = true
            } else {
              this.createDialog = true
            }
          }
        }
      })
    },

    // 打开创建编辑窗口
    openDialog (item) {
      this.$nextTick(() => {
        this.userItem = this.$options.data.call(this).userItem
        this.batchParams = this.$options.data.call(this).batchParams
        this.whiteList2 = []
        this.dialogType2 = 1
        this.getRuleOptions(item)
      })
    },

    //打开删除白名单
    deleteUser (item, type) {
      this.deleteType = type
      this.deleteParams = item
      this.deleteDialog = true
    },

    deleteUsers () {
      if (this.deleteType == 1) {
        let del1 = this.whiteList2.findIndex(item => {
          if (item.id == this.deleteParams.id) {
            return true
          }
        })
        this.whiteList2.splice(del1, 1)
        this.$message.success(this.$t('m.S_Success'))
        this.deleteDialog = false
      } else {
        let params = {
          days: this.deleteParams.days,
          id: this.deleteParams.ruleId,
          userIds: [this.deleteParams.uid]
        }
        this.$api.whiteList.unbindUser(params).then(res => {
          if (this.$ok(res)) {
            this.$message.success(res.message)
            this.deleteDialog = false
            this.getPage()
          } else {
            this.$message.error(res.message)
          }
        })
      }
    },

    //切换用户
    handleCurrentChange2 (val) {
      this.whiteLists.pageNum = val
    },

    //去创建规则
    toCreate () {
      this.noneDialog = false
      this.$emit('changeTab')
    },

    // 修改状态
    editState (row) {
      if (!this.permissionsLists(151)) {
        return
      }
      this.$api.whiteList.editUsersState({
        id: row.id,
        state: row.state == 0 ? 1 : 0
      }).then(res => {
        if (this.$ok(res)) {
          this.$message.success(res.message)
          this.getPage()
        } else {
          this.$message.error(res.message)
        }
      })
    },

    //获取用户
    getUsersList () {
      this.$api.whiteList.getUsers(this.params1).then(res => {
        this.searchType = 2
        if (this.$ok(res)) {
          this.usersData = res.data
        }
      })
    },

    searchBtn () {
      if (!this.params1.search) {
        this.$message(this.$t('m.Please_enter_user_account'))
        return
      }
      this.getUsersList()
    },

    refreshBtn () {
      this.searchType = 1
      this.params1.search = ''
      this.usersData = []
    },

    //关闭创建
    closeCreate () {
      if (this.dialogType2 == 1) {
        this.createDialog = false
      } else {
        this.dialogType2 = 1
        this.refreshBtn()
      }
    },
    //创建白名单 / 选中用户
    confirmCreate () {
      if (this.dialogType2 == 1) {
        if (!this.userItem.ruleId) {
          this.$message.error(this.$t('m.Link_whitelist'))
          return
        }
        if (this.whiteList2.length == 0) {
          this.$message.error(this.$t('m.Please_select_users'))
          return
        }
        this.batchParams.id = this.userItem.ruleId
        this.batchParams.rentNum = this.userItem.rentNum
        this.whiteList2.forEach(item => {
          this.batchParams.userIds.push(item.id)
        })
        // console.log(this.batchParams)
        this.$api.whiteList.bindUser(this.batchParams).then(res => {
          if (this.$ok(res)) {
            this.$message.success(res.message)
            this.createDialog = false
            this.getPage()
          } else {
            this.$message.error(res.message)
          }
        })
      } else {
        if (!this.batchParams.days) {
          this.$message.error(this.$t('m.Please_validity_period'))
          return
        }
        if (this.usersData.length == 0) {
          this.$message.error(this.$t('m.Please_select_users2'))
          return
        }
        let index = this.whiteList2.findIndex(
          item => item.id === this.usersData[0].id
        )
        if (index !== -1) {
          this.$set(this.whiteList2, index, this.usersData[0])
        } else {
          this.whiteList2.push(this.usersData[0])
        }
        this.closeCreate()
      }
    },
    closeBtn () {
      this.editUserDialog = false
      this.userItem = this.$options.data.call(this).userItem
    },
    editBtn () {
      if (!this.userItem.ruleId) {
        this.$message.error(this.$t('m.Link_whitelist'))
        return
      }
      if (!this.userItem.days) {
        this.$message.error(this.$t('m.Please_validity_period'))
        return
      }
      this.$api.whiteList.modifyUser(this.userItem).then(res => {
        if (this.$ok(res)) {
          this.$message.success(res.message)
          this.closeBtn()
          this.getPage()
        } else {
          this.$message.error(res.message)
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">
.el_button {
  min-width: 150px;
  background: #ffffff !important;
  border: 1px solid #d2d8e2 !important;
  border-radius: 4px;
  color: var(--text-color) !important;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 20px;
}
</style>
